﻿@namespace MudBlazor
@inherits MudComponentBase
@using System.Text.RegularExpressions
@using MudBlazor.Components.Highlighter
@using System.Text
@using System.Net

@if (Markup)
{
    if (_htmlAwareFragments != null)
    {
        var sb = new StringBuilder();
        foreach (var fragmentInfo in _htmlAwareFragments)
        {
            switch (fragmentInfo.Type)
            {
                case FragmentType.HighlightedText:
                    var attributes = RenderAttributes(UserAttributes);
                    var classNames = string.IsNullOrWhiteSpace(Class) ? string.Empty : $" class=\"{Class}\" ";
                    var styles = string.IsNullOrWhiteSpace(Style) ? string.Empty : $" style=\"{Style}\" ";
                    sb.Append($"<mark{classNames}{styles}{attributes}>{WebUtility.HtmlEncode(fragmentInfo.Content)}</mark>");
                    break;
                case FragmentType.Markup:
                    sb.Append(fragmentInfo.Content);
                    break;
                case FragmentType.Text:
                default:
                    sb.Append(WebUtility.HtmlEncode(fragmentInfo.Content));
                    break;
            }
        }

        @((MarkupString)sb.ToString())
    }
    else if (!string.IsNullOrEmpty(Text))
    {
        @((MarkupString)Text)
    }
}
else if (_fragments.Length > 0)
{
    foreach (var fragment in _fragments.Span)
    {
        if (IsMatch(fragment))
        {
            <mark class="@Class" style="@Style" @attributes="@UserAttributes">@fragment</mark>
        }
        else
        {
            @fragment
        }
    }
}
else if (!string.IsNullOrEmpty(Text))
{
    @Text
}

@code {
    private string RenderAttributes(IDictionary<string, object> attributes)
    {
        if (attributes == null) return string.Empty;

        var sb = new StringBuilder();
        foreach (var kvp in attributes)
        {
            var attrName = System.Net.WebUtility.HtmlEncode(kvp.Key);
            var attrValue = System.Net.WebUtility.HtmlEncode(kvp.Value?.ToString());
            sb.Append($" {attrName}=\"{attrValue}\" ");
        }

        return sb.ToString();
    }
}
